import java.util.Arrays;
import java.util.Comparator;

public class Solution2271 {
    public int maximumWhiteTiles(int[][] tiles, int carpetLen) {
        Arrays.sort(tiles, Comparator.comparingInt(a -> a[0]));
        for (int[] tile : tiles) {
            if (tile[1]-tile[0]+1>=carpetLen){
                return carpetLen;
            }
        }
        int[] sum=new int[tiles.length+1];
        for (int i=0;i<tiles.length;i++){
            sum[i+1]=sum[i]+tiles[i][1]-tiles[i][0]+1;
        }
        int j=0,ans=tiles[0][1]-tiles[0][0]+1;
        for (int i=1;i<tiles.length;i++){
            while (tiles[i][1]-carpetLen+1>tiles[j][1]){
                j++;
            }
            if (tiles[i][1]-carpetLen+1<=tiles[j][0]){
                ans=Math.max(ans,sum[i+1]-sum[j]);
            }else {
                ans=Math.max(ans,sum[i+1]-sum[j+1]+(tiles[j][1]-tiles[i][1]+carpetLen));
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution2271().maximumWhiteTiles(new int[][]{{1,5},{10,11},{12,18},{20,25},{30,32}},10));
    }
}
